package com.hcmiu.buddytracking;

import getFromDBMethods.getAllBuddies;

import java.text.DecimalFormat;
import java.util.ArrayList;

import org.json.JSONException;

import Storage.Buddy;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class BuddyList extends ListActivity {
	private ArrayList<Buddy> buddylist = new ArrayList<Buddy>();
	private BuddyAdapter myAdapter;
	private SharedPreferences pref;
	private String PREF_NAME = "buddytracking";
	private String currentPhoneNumber;
	private ProgressDialog progressDialog;
	private LocationManager locMgr = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.buddylist);
		pref = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
		currentPhoneNumber = pref.getString("currentPhoneNumber", null);
		locMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		progressDialog = new ProgressDialog(this);
		progressDialog.setMessage("Getting Buddy list...");
		progressDialog.setIndeterminate(true);
		progressDialog.setCancelable(false);

		myAdapter = new BuddyAdapter(this, R.layout.onebuddy, buddylist);
		setListAdapter(myAdapter);

		registerForContextMenu(getListView());

		progressDialog.show();
		getBuddyList();

	}

	private void getBuddyList() {
		Thread t = new Thread() {
			@Override
			public void run() {
				Looper.prepare();
				try {
					buddylist = getAllBuddies.process(currentPhoneNumber);
					runOnUiThread(returnRes);
				} catch (JSONException e) {
					e.printStackTrace();
				}
				Looper.loop();
			}
		};
		t.start();
	}

	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			if (buddylist != null && buddylist.size() > 0) {
				myAdapter.notifyDataSetChanged();
				for (int i = 0; i < buddylist.size(); i++)
					myAdapter.add(buddylist.get(i));
			}
			progressDialog.dismiss();
			myAdapter.notifyDataSetChanged();
		}
	};

	private class BuddyAdapter extends ArrayAdapter<Buddy> {

		private ArrayList<Buddy> items;

		public BuddyAdapter(Context context, int textViewResourceId,
				ArrayList<Buddy> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.onebuddy, null);
			}
			Buddy buddy = items.get(position);
			if (buddy != null) {
				TextView tt = (TextView) v.findViewById(R.id.buddyname);
				ImageView iv = (ImageView) v.findViewById(R.id.buddystatus);

				if (buddy.getIsOnline().equals("1")) {
					iv.setImageResource(R.drawable.status_online);
				} else if (buddy.getIsOnline().equals("0")) {
					iv.setImageResource(R.drawable.status_offline);
				}

				if (tt != null) {
					tt.setText(buddy.getFullName());
				}

			}
			return v;
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		boolean supRetVal = super.onCreateOptionsMenu(menu);
		menu.add(1, 0, 0, R.string.refresh_buddylist).setIcon(
				R.drawable.refresh);
		menu.add(1, 1, 1, R.string.back_button).setIcon(R.drawable.back);
		return supRetVal;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 0) {
			refreshAdapter();
			return true;
		}
		if (item.getItemId() == 1) {
			this.finish();
			return true;
		}
		return false;
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {

		menu.add(0, R.string.navigate_to_buddy, 0, "Navigate");
		menu.add(0, R.string.view_buddy_details, 0, "View details");
		menu.add(0, R.string.draw_path_to_buddy, 0, "Find path");
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		int Buddyid = (int) ((AdapterView.AdapterContextMenuInfo) item
				.getMenuInfo()).id;

		switch (item.getItemId()) {
		// NAVIGATE TO Buddy
		case R.string.navigate_to_buddy:

			setResult(R.string.navigate_to_buddy, (new Intent()).putExtra(
					"Buddyid", Buddyid));
			finish();

			break;
		case R.string.draw_path_to_buddy:

			setResult(R.string.draw_path_to_buddy, (new Intent()).putExtra(
					"Buddyid", Buddyid));
			finish();

			break;
		case R.string.view_buddy_details:
			String name = buddylist.get(Buddyid).getFullName() + "'s details";
			String detail = buddylist.get(Buddyid).getAllDetails();
			detail += "*Distance: "
					+ distanceFromMe(buddylist.get(Buddyid).getLocation());
			detail += "\n";
			detailDialog(name, detail);
			break;
		}
		return super.onContextItemSelected(item);
	}

	private String distanceFromMe(Location location) {
		final DecimalFormat df = new DecimalFormat("####0.00");
		Location myLocation = locMgr
				.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		float distance = 0;
		String result = "";
		if (myLocation != null)
			distance = (myLocation.distanceTo(location)) / 1000;
		if (distance < 1) {
			distance = distance * 1000;
			result = df.format(distance) + " meter";
		} else
			result = df.format(distance) + " km";

		return result;
	}

	private AlertDialog detailDialog(String name, String detail) {
		return (new AlertDialog.Builder(this).setTitle(name).setMessage(detail)
				.show());
	}

	private void refreshAdapter() {
		refreshBuddyListHandler.sendMessage(new Message());
	}

	Handler refreshBuddyListHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			myAdapter.clear();
			getBuddyList();
		}
	};

}
